import * as Sequelize from "sequelize";
import * as fs from "fs";
import * as path from "path";
import {EnvUtils} from "../utils/EnvUtils";


let sequelize:Sequelize.Sequelize;

class MysqlClient{
    static init(){
        sequelize = new Sequelize(
            "yiju_prod",
            'yiju',
            'yiju',
            {
                "host": EnvUtils.MYSQL_HOST,
                "port":EnvUtils.MYSQL_PORT,
                "dialect": "mysql",
                "timezone": '+08:00'
            }
        );

        let modelMap:Map<string,any> = new Map();
        fs.readdirSync(__dirname)
            .filter(function(file) {
                return (file.indexOf(".") !== 0) && (file !== "MysqlClient.js")&& (file !== "BaseDao.js")&& (file !== "index.js");
            })
            .forEach(function(file) {
                let dao = require(path.join(__dirname, file));
                let model = sequelize.import(dao.modelName,dao.initDao);
                modelMap.set(dao.modelName,model);
            });

        for (let [key,entry] of Array.from(modelMap.entries())) {
            entry.options.classMethods&&
            entry.options.classMethods.associate&&
            entry.options.classMethods.associate();
        }
    }

    static getSequelize():Sequelize.Sequelize{
        return sequelize;

    }
}

export {MysqlClient}
